// 引入crypto加密模块 - Nodejs内置模块
let crypto;
try {
  crypto = require('crypto');
} catch (err) {
  console.log('crypto support is disabled!');
}

// ase-128-cbc 加密算法要求key和iv长度都为16
const key = Buffer.from('9vApxLk5G3PAsJrM', 'utf8');
const iv = Buffer.from('FnJL7EDzjqWjcaY9', 'utf8');

// 加密
function encrypt(password) {
    let md5Password = '';
    const cipheriv = crypto.createCipheriv('aes-128-cbc', key, iv);
    md5Password += cipheriv.update(password, 'utf8', 'hex');
    md5Password += cipheriv.final('hex');
    return md5Password;
}

// 解密
function decrypt(password) {
    let md5Password = '';
    const cipheriv = crypto.createDecipheriv('aes-128-cbc', key, iv);
    md5Password += cipheriv.update(password, 'hex', 'utf8');
    md5Password += cipheriv.final('utf8');
    return md5Password;
}

module.exports = { encrypt, decrypt }





// // 复杂版
// const algorithm = 'aes-256-ctr';
// const ENCRYPTION_KEY = 'Put_Your_Password_Here'; // or generate sample key Buffer.from('FoCKvdLslUuB4y3EZlKate7XGottHski1LmyqJHvUhs=', 'base64');
// const IV_LENGTH = 16;

// // 加密
// function encrypt(password) {
//     let iv = crypto.randomBytes(IV_LENGTH);
//     let cipher = crypto.createCipheriv(algorithm, Buffer.from(ENCRYPTION_KEY, 'hex'), iv);
//     let encrypted = cipher.update(password);
//     encrypted = Buffer.concat([encrypted, cipher.final()]);
//     return iv.toString('hex') + ':' + encrypted.toString('hex');
// }

// // 解密
// function decrypt(password) {
//     let textParts = password.split(':');
//     let iv = Buffer.from(textParts.shift(), 'hex');
//     let encryptedText = Buffer.from(textParts.join(':'), 'hex');
//     let decipher = crypto.createDecipheriv(algorithm, Buffer.from(ENCRYPTION_KEY, 'hex'), iv);
//     let decrypted = decipher.update(encryptedText);
//     decrypted = Buffer.concat([decrypted, decipher.final()]);
//     return decrypted.toString();
// }

// module.exports = { encrypt, decrypt }